//
//  BIDRentListViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/6/14.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDRentListViewController.h"
#import "BIDRentListSectionHeaderView.h"
#import "BIDPublishRentInfoViewController.h"
#import "BIDRentDetailViewController.h"
#import "BIDRentCell.h"

#import <SDWebImage/UIImageView+WebCache.h>

static NSString *rentListURL = @"rentAndroid/list.action";
//房屋类型、价格、租房类型
static NSString *conditionListURL = @"commonAndroid/getDictsByCode.action";

@interface BIDRentListViewController ()<BIDBaseListViewDelegate, BIDRentListSectionHeaderViewDelegate, UITableViewDelegate, UITableViewDataSource>
{
    BOOL _isRegister;
    //菜单数据源
    NSArray *_menuArr;
    NSUInteger _selectPriceIndex;
    NSUInteger _selectHouseTypeIndex;
    NSUInteger _selectRentTypeIndex;
    //数据源来自于价格列表还是房屋类型、租房类型
    NSUInteger _curKind;
    UITableView *_menuTableView;
    NSMutableArray *_priceArr;
    NSMutableArray *_houseTypeArr;
    NSMutableArray *_rentTypeArr;
    //菜单view的遮罩
    UIView *_maskView;
    //菜单是否已显示
    BOOL _isMenuShow;
    //
    BIDRentListSectionHeaderView *_sectionHeaderView;
}
@end

@implementation BIDRentListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"租房";
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _menuArr = [[NSMutableArray alloc] init];
    _priceArr = [[NSMutableArray alloc] init];
    [_priceArr addObject:@{@"name":@"不限", @"id":@""}];
    _houseTypeArr = [[NSMutableArray alloc] init];
    [_houseTypeArr addObject:@{@"name":@"不限", @"id":@""}];
    _rentTypeArr = [[NSMutableArray alloc] init];
    [_rentTypeArr addObject:@{@"name":@"不限", @"id":@""}];
    _selectPriceIndex = 0;
    _selectHouseTypeIndex = 0;
    _selectRentTypeIndex = 0;
    //
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(publishRentInfo)];
    //
    _sectionHeaderView = [[[NSBundle mainBundle] loadNibNamed:@"BIDRentListSectionHeaderView" owner:self options:nil] lastObject];
    _sectionHeaderView.delegate = self;
    CGRect frame = _sectionHeaderView.frame;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    frame.size.width = screenSize.width;
    _sectionHeaderView.frame = frame;
    _sectionHeaderView.widthForHouseTypeConstraint.constant = (screenSize.width-20)/3;
    [_sectionHeaderView setNeedsLayout];
    [_sectionHeaderView layoutIfNeeded];
    //
    _menuTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(_sectionHeaderView.frame), screenSize.width, 176.f)];
    _menuTableView.delegate = self;
    _menuTableView.dataSource = self;
    _menuTableView.tag = 101;
    //
    _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(_sectionHeaderView.frame), screenSize.width, screenSize.height-64-CGRectGetHeight(_sectionHeaderView.frame))];
    [_maskView setBackgroundColor:RGBACOLOR(0, 0, 0, 0.7f)];
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
    [_maskView addGestureRecognizer:tapGR];
    //
    [self getCondition];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.curPage = 0;
    [self.dataSourceArr removeAllObjects];
    [self loadData];
}

/**
 获取租房列表
 */
- (void)loadData
{
    self.curPage++;
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], rentListURL];
    NSMutableString *strPost = [[NSMutableString alloc] initWithFormat:@"page=%ld&rows=%ld", self.curPage, self.countPerPage];
    if(_selectPriceIndex != 0)
    {
        [strPost appendFormat:@"&searchParam.rental=%@", _priceArr[_selectPriceIndex][@"value"]];
    }
    if(_selectHouseTypeIndex != 0)
    {
        [strPost appendFormat:@"&searchParam.houseType=%@", _houseTypeArr[_selectHouseTypeIndex][@"value"]];
    }
    if(_selectRentTypeIndex != 0)
    {
        [strPost appendFormat:@"&searchParam.rentMode=%@", _rentTypeArr[_selectRentTypeIndex][@"value"]];
    }
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            NSArray *arr = responseDic[@"rows"];
            if(arr.count > 0)
            {
                [self.dataSourceArr addObjectsFromArray:arr];
                if(self.dataSourceArr.count < self.curPage*self.countPerPage)
                {
                    [self.myTableView hasNoMoreData];
                }
                else
                {
                    [self.myTableView hasMoreData];
                }
            }
            [self.myTableView reloadData];
        }
        [self autoDecideToShowEmptyView];
    }];
}

- (void)getCondition
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], conditionListURL];
    dispatch_group_t group = dispatch_group_create();
    [self showSpinnerView];
    dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
        NSString *strPost = [[NSString alloc] initWithFormat:@"searchParam.code=%@", @"RENT_PRICE"];
        id obj = [BIDDataCommunication getDataFromNetBySyn:strRequestURL postValue:strPost];
        if([obj isKindOfClass:[NSDictionary class]])
        {
            NSDictionary *tempDic = (NSDictionary *)obj;
            NSNumber *resValue = tempDic[@"head"][@"success"];
            if([resValue intValue] == 1)
            {
                NSArray *tempArr = tempDic[@"body"];
                [_priceArr addObjectsFromArray:tempArr];
            }
        }
    });
    dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
        NSString *strPost = [[NSString alloc] initWithFormat:@"searchParam.code=%@", @"HOUSE_TYPE"];
        id obj = [BIDDataCommunication getDataFromNetBySyn:strRequestURL postValue:strPost];
        if([obj isKindOfClass:[NSDictionary class]])
        {
            NSDictionary *tempDic = (NSDictionary *)obj;
            NSNumber *resValue = tempDic[@"head"][@"success"];
            if([resValue intValue] == 1)
            {
                NSArray *tempArr = tempDic[@"body"];
                [_houseTypeArr addObjectsFromArray:tempArr];
            }
        }
    });
    dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
        NSString *strPost = [[NSString alloc] initWithFormat:@"searchParam.code=%@", @"RENT_MODE"];
        id obj = [BIDDataCommunication getDataFromNetBySyn:strRequestURL postValue:strPost];
        if([obj isKindOfClass:[NSDictionary class]])
        {
            NSDictionary *tempDic = (NSDictionary *)obj;
            NSNumber *resValue = tempDic[@"head"][@"success"];
            if([resValue intValue] == 1)
            {
                NSArray *tempArr = tempDic[@"body"];
                [_rentTypeArr addObjectsFromArray:tempArr];
            }
        }
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self hideSpinnerView];
    });
}

/**
 发布租房信息
 */
- (void)publishRentInfo
{
    BIDPublishRentInfoViewController *vc = [[BIDPublishRentInfoViewController alloc] initWithNibName:@"BIDPublishRentInfoViewController" bundle:nil];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self setNavigationControllerAttribute:nav];
    [self presentViewController:nav animated:YES completion:^{}];
}

/**
 显示条件菜单
 */
- (void)showMenuView
{
    _isMenuShow = YES;
    [self.view addSubview:_maskView];
    [self.view addSubview:_menuTableView];
    [_menuTableView reloadData];
}

/**
 隐藏条件菜单
 */
- (void)hideMenuView
{
    _isMenuShow = NO;
    [_menuTableView removeFromSuperview];
    [_maskView removeFromSuperview];
}

/**
 点击取消菜单的显示

 @param tapGR <#tapGR description#>
 */
- (void)tapGestureHandler:(UITapGestureRecognizer *)tapGR
{
    [self hideMenuView];
}

#pragma mark - BIDRentListSectionHeaderViewDelegate
- (void)showMenuWithType:(NSUInteger)type
{
    if(_curKind == type && _isMenuShow)
    {
        [self hideMenuView];
        return;
    }
    _curKind = type;
    if(type == 0)
    {
        //价格
        _menuArr = [[NSArray alloc] initWithArray:_priceArr];
    }
    else if(type == 1)
    {
        //房屋类型
        _menuArr = [[NSArray alloc] initWithArray:_houseTypeArr];
    }
    else if(type == 2)
    {
        //租房类型
        _menuArr = [[NSArray alloc] initWithArray:_rentTypeArr];
    }
    CGRect frame = _menuTableView.frame;
    frame.size.height = _menuArr.count * 45;
    _menuTableView.frame = frame;
    [self showMenuView];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView.tag == 101)
    {
        if(_curKind == 0)
        {
            return _priceArr.count;
        }
        else if(_curKind == 1)
        {
            return _houseTypeArr.count;
        }
        else if(_curKind == 2)
        {
            return _rentTypeArr.count;
        }
        return 0;
    }
    else
    {
        return self.dataSourceArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    static NSString *menuIdentifier = @"menu";
    NSUInteger row = indexPath.row;
    if(tableView.tag == 101)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:menuIdentifier];
        if(!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:menuIdentifier];
        }
        NSDictionary *dic = _menuArr[row];
        cell.textLabel.text = dic[@"name"];
        cell.textLabel.textColor = RGBACOLOR(50, 54, 59, 1.f);
        cell.accessoryType = UITableViewCellAccessoryNone;
        NSUInteger index = 0;
        switch(_curKind)
        {
            case 0:
            {
                index = _selectPriceIndex;
            }
                break;
            case 1:
            {
                index = _selectHouseTypeIndex;
            }
                break;
            case 2:
            {
                index = _selectRentTypeIndex;
            }
                break;
        }
        if(index == row)
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }
    else
    {
        if(!_isRegister)
        {
            _isRegister = YES;
            UINib *nib = [UINib nibWithNibName:@"BIDRentCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:identifier];
        }
        BIDRentCell *rentCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        NSDictionary *dic = self.dataSourceArr[row];
        NSArray *fileArr = dic[@"fileList"];
        if(fileArr && fileArr.count>0)
        {
            NSDictionary *fileDic = fileArr[0];
            NSString *strFilePath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], fileDic[@"path"]];
            [rentCell.imgView setImageWithURL:[NSURL URLWithString:strFilePath] placeholderImage:[UIImage imageNamed:@"pic_placeholder.png"]];
        }
        else
        {
            [rentCell.imgView setImage:[UIImage imageNamed:PIC_PLACEHOLDER]];
        }
        rentCell.titleLabel.text = [[NSString alloc] initWithFormat:@"%@\r ", dic[@"content"]];
        rentCell.rentTypeLabel.text = [[NSString alloc] initWithFormat:@"%@ %@", dic[@"houseTypeName"], dic[@"rentModeName"]];
        NSString *strPrice = ANY2NSSTRING(dic[@"rental"]);
        NSNumber *payModeValue = dic[@"payMode"];
        NSString *strExtention = @"";
        switch([payModeValue integerValue])
        {
            case 1:
            {
                strExtention = @"月";
            }
                break;
            case 2:
            {
                strExtention = @"季度";
            }
                break;
            case 3:
            {
                strExtention = @"年";
            }
                break;
        }
        rentCell.priceLabel.text = [[NSString alloc] initWithFormat:@"%@元/%@", strPrice, strExtention];
        cell = rentCell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger row = indexPath.row;
    if(tableView.tag == 101)
    {
        switch(_curKind)
        {
            case 0:
            {
                if(_selectPriceIndex != row)
                {
                    [self.dataSourceArr removeAllObjects];
                    self.curPage = 0;
                    _selectPriceIndex = row;
                    [self loadData];
                }
            }
                break;
            case 1:
            {
                if(_selectPriceIndex != row)
                {
                    [self.dataSourceArr removeAllObjects];
                    self.curPage = 0;
                    _selectHouseTypeIndex = row;
                    [self loadData];
                }
            }
                break;
            case 2:
            {
                if(_selectPriceIndex != row)
                {
                    [self.dataSourceArr removeAllObjects];
                    self.curPage = 0;
                    _selectRentTypeIndex = row;
                    [self loadData];
                }
            }
                break;
        }
        [self hideMenuView];
    }
    else
    {
        NSDictionary *dic = self.dataSourceArr[row];
        BIDRentDetailViewController *vc = [[BIDRentDetailViewController alloc] initWithNibName:@"BIDRentDetailViewController" bundle:nil];
        vc.rentID = dic[@"id"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(tableView.tag == 101)
    {
        return nil;
    }
    else
    {
        return _sectionHeaderView;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag == 101)
    {
        return 44.f;
    }
    else
    {
        return 109.f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(tableView.tag == 101)
    {
        return 0.f;
    }
    else
    {
        return 55.f;
    }
}

@end
